from django.http import HttpResponse
from django.shortcuts import render, redirect
from ..forms import LoginModelForm
from .. import models
from ..utils.code import check_code


def login(request):
    """登录"""
    if request.method == "GET":
        form = LoginModelForm()
        return render(request, "app_02/login.html", {"form": form})

    form = LoginModelForm(data=request.POST)
    if form.is_valid():
        # 验证码校验
        user_input_code = form.cleaned_data.pop("code")
        code = request.session.get("image_code", "")
        print("$$$$$", code)
        print("^^^^^", user_input_code)
        print(code == user_input_code)
        if code != user_input_code:
            form.add_error("code", "验证码错误")
            return render(request, "app_02/login.html", {"form": form})

        # 去数据库校验用户名和密码是否正确
        # admin_object = models.Amin.objects.filter(username=xxx, password=xxx).first()
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码错误")
            return render(request, "app_02/login.html", {"form": form})

        # 用户名和密码正确
        # 网站生成随机字符串; 写到用户浏览器的cookie; 在写入到session中;
        request.session["info"] = {
            "id": admin_object.id,
            "name": admin_object.username
        }
        # session可以保存1天
        request.session.set_expiry(60 * 60 * 24)
        request.session["info"] = {"id": admin_object.id, "name": admin_object.username}

        return redirect("/app_02/admin/list/")

    return render(request, "app_02/login.html", {"form": form})


from io import BytesIO
def image_code(request):
    """生成图片验证码"""
    # 调用pillow函数，生成图片
    img, code_string = check_code()
    # 写入到自己的session中，(以便后续获取验证码再进行校验)
    request.session["image_code"] = code_string
    request.session.set_expiry(60)


    stream = BytesIO()
    img.save(stream, 'png')
    stream.getvalue()

    return HttpResponse(stream.getvalue(), content_type="image/png")


def logout(request):
    """注销"""
    request.session.clear()
    return redirect("/app_02/login/")


